<script setup lang="ts">

import { useRoute } from 'vue-router'
import { onMounted, ref } from 'vue'
import axios from 'axios'
import videoHls from './components/video-hls.vue'
import videoImg from './components/video-img.vue'

import Vconsole from 'vconsole'
let vConsole = new Vconsole()

interface Info {
  id: string;
  carid: string;
  oneval: string;
  setval: string;
}

const route = useRoute();
const userToken = route.query.token;
const openid = route.query.openid;
const cangid = route.query.cangid;
const chengid = ref('');
const videoRef = ref(null);
const audioUrl = ref('');
const info = ref<Info | null>(null);
let ws = null;
const doman = '111.230.61.40:8989'
const connecting = ref(false);
// token是否失效
const showTokenTip = ref(false)
const cameras = ref<any>([{
  name: '',
  serialNumber: '',
  ysUrl: '',
  ysHlsUrl: '',
  ysAccessToken: '',
}]);
const wsList = ref<any>([]);
const videoImgData = ref({})
const fullUrl = ref('');
const fullVisible = ref(false)
// 创建axios实例
const instance = axios.create({
  baseURL: `http://${doman}`, // 设置基础URL
  timeout: 5000, // 设置请求超时时间
});
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，比如添加请求头信息
    // config.headers['X-Custom-Header'] = 'foobar';
    config.headers['openid'] = openid;
    config.headers['userToken'] = userToken;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么，比如处理服务器返回的状态码
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么，比如统一处理错误码
    return Promise.reject(error);
  }
);
// 封装get请求
function get(url: string, params = {}) {
  return instance.get(url, { params });
}

// 封装post请求
function post(url: string, data = {}) {
  return instance.post(url, data);
}

onMounted(() => {
  get(`/wxmini/standard/api/camera/getByCangId?cangid=${cangid}`).then(function (response: any) {
    console.log(response, 'response');
    // 提示token过期
    if (response?.code === 401) {
      showTokenTip.value = true;
      console.log('token 过期');
    }
    cameras.value = response?.data || [];
    initVideo();
  })
    .catch(function (error) {
      console.log(error);
    });
  reConnect();
})
const initVideo = () => {
  // cameras.value.forEach(item => {
  //   if (!item.serialNumber) return;
  //   videoImgData.value[item?.serialNumber] = {
  //     loading: true,
  //   };
  //   // 创建ws获取视频流
  //   const ws = new WebSocket(`ws://${doman}/websocket/${item?.serialNumber}`);
  //   ws.onopen = function () {
  //     console.log('ws open');
  //   };
  //   ws.onmessage = function (evt) {
  //     videoImgData.value[item?.serialNumber] = {
  //       loading: false,
  //       data: evt.data,
  //     }
  //   };
  //   ws.onclose = function () {
  //     console.log('ws close');
  //   };
  //   wsList.value.push(ws);
  // })
}
// 开阀
const openValve = async () => {
  await post('/wxmini/standard/api/entry/kaifa', {
    cangid,
    chengid: chengid.value,
  })
}
// 关阀
const closeValve = async () => {
  await post('/wxmini/standard/api/entry/guanfa', {
    cangid,
    chengid: chengid.value,
  })
}
const closeFull = () => {
  fullVisible.value = false;
}
const showFull = (url: string) => {
  fullVisible.value = true;
  fullUrl.value = url + '';
}
// 创建websocket
// 重连
const reConnect = () => {
  connecting.value = true;
  ws = new WebSocket(`ws://111.230.61.40:8989/wxmini/standard/api/realtime/${userToken}/${cangid}`);
  ws.onopen = function() {
    console.log('ws open');
    connecting.value = false;
  };
  ws.onmessage = function (evt) {
    console.log('ws message', JSON.parse(evt.data), 'data');
    try {
      const data = JSON.parse(evt.data);
      if (data.resultCode === 401) {
        showTokenTip.value = true;
        console.log('token 过期');
      } else {
        info.value = data;
        if(data?.devid){
          chengid.value = data.devid;
        }
        if (data?.filename) {
          // 删除页面所有的audio节点
          const audios = document.querySelectorAll('audio');
          audios.forEach(item => {
            item.remove();
          });
          console.log('删除所有的audio')
          // 创建一个audio节点并插入到dom
          const audio = document.createElement('audio');
          audio.src = data.filename + '?_t' + new Date().getTime();
          audio.autoplay = true;
          document.body.appendChild(audio);
          console.log('播放：' + audio.src)
          // audioUrl.value = data.filename + '?_t' + new Date().getTime();
        }
        console.log('走业务');
      }
    } catch (e) {
      console.log(e);
    }
  };
  ws.onclose = function () {
    console.log('ws close');
  };
}
</script>

<template>
<!--  {{cameras}}-->
  <div class="token-tip" v-if="showTokenTip">
    <p>登录过期,请重新登录...</p>
    <div class="btn-wrap">
<!--      <div class="btn" @click="toLogin">去登录</div>-->
    </div>
  </div>
  <div class="home">
    <template  v-if="cameras.length > 0">
      <div class="video" v-for="(item, index) in cameras" :key="index">
<!--        <videoHls width="100%" height="100%" :hlsUrl="item?.ysHlsUrl"/>-->
        <videoImg :video-url="item.rtspUrl">
          <template #btns>
            <div class="full" v-if="chengid">
              <div class="btn blue" @click="openValve">开阀</div>
              <div class="btn" @click="closeValve">关阀</div>
            </div>
          </template>
        </videoImg>
<!--        <div class="tools">-->
<!--          <img @click="showFull(item?.ysHlsUrl)" class="btn" src="../../assets/images/icon-full.png" alt=""/>-->
<!--        </div>-->
      </div>
    </template>
    <div class="main">
      <div class="card" v-if="info">
        <p class="status"><span class="blue">{{info?.carid || '--'}}</span>正在装车</p>
        <div class="cell">
          <div class="cell-bd">
            <p class="key">已装</p>
            <p class="value"><span class="blue">{{info?.oneval || '--'}}</span> 吨</p>
          </div>
          <div class="cell-bd">
            <p class="key">总装量</p>
            <p class="value"><span class="blue">{{info?.setval || '--'}}</span> 吨</p>
          </div>
        </div>
      </div>
<!--      <div class="btns" v-if="chengid">-->
      <div class="btns" v-if="chengid">
        <div class="btn blue" @click="openValve">开阀</div>
        <div class="btn" @click="closeValve">关阀</div>
      </div>
      <div class="btns" v-else>
        <p class="tip">未获取到设备信息，请重连!</p>
        <button class="btn" :class="connecting ? '' : 'blue'" :disabled="connecting" @click="reConnect">{{ connecting ? '重连中...' : '重连' }}</button>
      </div>
    </div>
    <audio :src="audioUrl" autoplay :key="audioUrl"></audio>
  </div>
<!--  <div class="full" v-if="fullVisible">-->
<!--    <div class="cell">-->
<!--      <div class="cell-bd">-->
<!--&lt;!&ndash;        <iframe&ndash;&gt;-->
<!--&lt;!&ndash;          :src="fullUrl"&ndash;&gt;-->
<!--&lt;!&ndash;          frameborder="0" width="100%" height="100%"></iframe>&ndash;&gt;-->
<!--        <videoHls width="100%" height="100%" :hlsUrl="fullUrl"/>-->
<!--      </div>-->
<!--      <div class="cell-ft">-->
<!--        <div class="btns">-->
<!--          <div class="btn blue" @click="closeFull">返回</div>-->
<!--          <div class="btn blue" v-if="chengid" @click="openValve">开阀</div>-->
<!--          <div class="btn" v-if="chengid" @click="closeValve">关阀</div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
</template>

<style scoped>
.home{
  font-size: 28px;
  background: #f5f5f5;
  padding-bottom: 55px;
  height: 100vh;
  .video{
    width: 100%;
    min-height: 188px;
    font-size: 0;
    background: #000;
    .tools{
      padding: 15px;
      font-size: 0px;
      color: #fff;
      //line-height: 55px;
      text-align: right;
      .btn{
        width: 54px;
        display: inline-block;
      }
    }
  }
  .main{
    padding: 0 30px;
    .card{
      background: #fff;
      padding: 30px;
      .status{
        font-weight: 400;
        font-size: 31px;
        color: #010101;
        margin-bottom: 60px;
        .blue{
          color: #3C9CFF;
        }
      }
      .cell{
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        .cell-bd{
          width: 50%;
          .key{
            font-family: Source Han Sans CN;
            font-weight: 400;
            font-size: 23px;
            color: #333333;
          }
          .value{
            font-size: 33px;
            color: #000;
            .blue{
              font-size: 33px;
              color: #3C9CFF;
            }
          }
        }
      }
    }
    .btns{
      margin-top: 60px;
      .tip{
        text-align: center;
        margin-bottom: 50px;
        font-size: 28px;
        color: #333;
      }
      .btn{
        width: 100%;
        height: 76px;
        background: #C4C6C9;
        border-radius: 6px;
        text-align: center;
        margin-bottom: 33px;
        color: #fff;
        line-height: 76px;
        border: none;
        font-size: 28px;
        &[disabled]{
          background: #C4C6C9;
          color: #fff;
        }
        &.blue {
          background: #3C9CFF;
        }
      }
    }
  }
}
.module-2{
  margin-top: 120px;
}
img{
  width: 100%;
  display: block;
}
.token-tip{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  font-size: 28px;
  color: #333;
  z-index: 999;
}
.btn-wrap{
  margin-top: 20px;
  .btn{
    width: 100%;
    height: 76px;
    background: #3C9CFF;
    border-radius: 6px;
    text-align: center;
    color: #fff;
    line-height: 76px;
    font-size: 28px;
    margin-top: 40px;
  }
}
.btn{
  width: 100%;
  height: 76px;
  background: #C4C6C9;
  border-radius: 6px;
  text-align: center;
  margin-bottom: 33px;
  color: #fff;
  line-height: 76px;
  font-size: 28px;
  &.blue {
    background: #3C9CFF;
  }
}
</style>
